<!--
 * @Description: 接口管理
 * @Author: chendingfengmail@163.com
 * @Date: 2021-10-29 13:34:30
 * @LastEditTime: 2022-01-17 13:57:44
 * @LastEditors: chendingfengmail@163.com
 * @Reference:
-->
<!-- 客户管理 -->
<template>
  <dd-container>
    <dd-card class="box-card box-card2">
      <!-- 数据信息 -->
      <dd-table ref="clientDeatilsTable" :data="tableData" rowKey="id" :option="option" :screen="searchForm"
        :loadingData="loadClientDeatilsList" 
        height="25vh"
        @rowClick="rowClick">
        <template slot="condition">
          <el-form-item label="接入编码">
            <el-input v-model="searchForm.clientId" placeholder="请输入客户接入appid" clearable></el-input>
          </el-form-item>
          <el-form-item label="厂家名称">
            <el-input v-model="searchForm.manufacture" placeholder="请输入厂家名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="启用状态">
            <el-select v-model="searchForm.enable" placeholder="请选择状态" style="width: 192px" clearable>
              <el-option label="启用" :value="1"></el-option>
              <el-option label="禁用" :value="0"></el-option>
            </el-select>
          </el-form-item>
        </template>

        <template slot="operation">
          <el-form-item>
            <el-button type="search" size="small" @click="onSearch" v-if="showButton($route.path, '查询')">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="add" size="small" @click="openDialog('add')"
              v-if="showButton($route.path, '新增')">新增</el-button>
          </el-form-item>
        </template>

        <el-table-column prop="clientId" label="客户appId" align="start" width="200" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="manufacture" label="厂家名称" align="start" width="180"
          :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="contact" label="联系人" align="center" :show-overflow-tooltip="true"></el-table-column>
        <el-table-column prop="telephone" label="联系电话" align="center"></el-table-column>
        <el-table-column prop="enable" label="是否启用" align="center" width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.enable" :active-value="1" :inactive-value="0"
              @change="enabledChange(scope.row, scope.row.enable)" active-color="#13ce66">
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="400" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" type="add" @click="openClientAppDialog('parentAdd', scope.row)"
              v-if="showButton($route.path, '新增')">添加应用
            </el-button>
            <el-button size="mini" type="warning" @click="handleUpdateClientSecret(scope.row)"
              v-if="showButton($route.path, '更新密钥')">更新密钥
            </el-button>
            <el-button size="mini" type="info" @click="openDialog('info', scope.row)"
              v-if="showButton($route.path, '详情')">详情
            </el-button>
            <el-button size="mini" type="edit" @click="openDialog('edit', scope.row)"
              v-if="showButton($route.path, '编辑')">编辑
            </el-button>
            <el-button size="mini" type="del" @click="handleDelete(scope.$index, scope.row)"
              v-if="showButton($route.path, '删除')">删除
            </el-button>
          </template>
        </el-table-column>
      </dd-table>
      <ClientDetailsHandleDialog ref="clientDetailsHandleDialog" :visible.sync="clientDetailsHandleDialogVisible"
        :modelType="modelType" :modelData="modelData" @loadList="loadClientDeatilsList"></ClientDetailsHandleDialog>
      <ClientAppHandleDialog ref="clientAppHandleDialog" :visible.sync="clientAppHandleDialogVisible"
        :modelType="clientAppModelType" :modelData="clientAppModelData" @loadList="loadClientAppList"></ClientAppHandleDialog>
      <UpdateClientSecretDialog ref="updateClientSecretDialog" :visible.sync="updateClientSecretDialogVisible"
        :modelData="modelData"></UpdateClientSecretDialog>
    </dd-card>
    <dd-card class="box-card box-card2">
      <!-- 数据信息 -->
      <dd-table ref="clientAppTable" :data="clientAppTableData" rowKey="id" :option="clientAppOption" :screen="clientAppSearchForm"
        :loadingData="loadClientAppList" height="25vh">
        <template slot="condition">
          <el-form-item label="应用名称">
            <el-input v-model="clientAppSearchForm.name" placeholder="请输入应用名称" clearable></el-input>
          </el-form-item>
        </template>

        <template slot="operation">
          <el-form-item>
            <el-button type="search" size="small" @click="onSearchClientApp" v-if="showButton($route.path, '查询')">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="add" size="small" @click="openClientAppDialog('add')"
              v-if="showButton($route.path, '新增')">新增</el-button>
          </el-form-item>
        </template>

        <el-table-column prop="name" label="应用名称" align="start"></el-table-column>
        <el-table-column prop="icon" label="应用图标" align="start">
          <template slot-scope="scope">
              <el-image style="width: 60px; height: 60px" :src="scope.row.icon" :preview-src-list="[scope.row.icon]">
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline"></i>
                </div>
              </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="enable" label="是否启用" align="center" width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.enable" :active-value="1" :inactive-value="0"
              @change="enabledAppChange(scope.row, scope.row.enable)" active-color="#13ce66">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="prefix" label="访问前缀" align="center"></el-table-column>
        <el-table-column prop="enable" label="去除前缀" align="center" width="100">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.trim" :active-value="1" :inactive-value="0"
              @change="trimAppChange(scope.row, scope.row.trim)" active-color="#13ce66">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="api" label="代理接口" align="center" :show-overflow-tooltip="true"></el-table-column>

        <el-table-column label="操作" align="center" width="220">
          <template slot-scope="scope">
            <el-button size="mini" type="info" @click="openClientAppDialog('info', scope.row)"
              v-if="showButton($route.path, '详情')">详情</el-button>
            <el-button size="mini" type="edit" @click="openClientAppDialog('edit', scope.row)"
              v-if="showButton($route.path, '编辑')">编辑</el-button>
            <el-button size="mini" type="del" @click="handleClientAppDelete(scope.$index, scope.row)"
              v-if="showButton($route.path, '删除')">删除</el-button>
          </template>
        </el-table-column>
      </dd-table>
    </dd-card>
  </dd-container>
</template>

<script>
import ClientDetailsHandleDialog from './dialog/clientDetailsHandleDialog.vue';
import ClientAppHandleDialog from './dialog/clientAppHandleDialog.vue';
import UpdateClientSecretDialog from './dialog/updateClientSecretDialog.vue';
import { mapGetters } from 'vuex'

export default {
  name: 'clientDetails',
  components: {
    ClientDetailsHandleDialog,
    ClientAppHandleDialog,
    UpdateClientSecretDialog,
  },

  data() {
    return {
      searchForm: {
        clientId: '',
        manufacture: '',
        enable: '',
        pageIndex: 1,
        pageSize: 10,
      },
      clientAppSearchForm: {
        clientId: '',
        name: '',
        pageIndex: 1,
        pageSize: 10,
      },
      tableData: [],
      clientAppTableData: [],
      modelType: 'info',
      clientAppModelType: 'info',
      modelData: {},
      clientAppModelData: {},
      option: {
        total: 0,
        loading: true,
        operation: true,
        dialogTable: true
      },
      clientAppOption: {
        total: 0,
        loading: true,
        operation: true,
        dialogTable: true
      },
      clientDetailsHandleDialogVisible: false,
      clientAppHandleDialogVisible: false,
      updateClientSecretDialogVisible: false,

    };
  },

  computed: {
    ...mapGetters('ddAdmin/menu', ['showButton'])
  },

  mounted() {
    this.loadClientDeatilsList();
    this.loadClientAppList();
  },

  methods: {
    onSearch() {
      this.searchForm.pageIndex = this.$options.data().searchForm.pageIndex;
      this.loadClientDeatilsList();
    },

    onSearchClientApp() {
      this.clientAppSearchForm.pageIndex = this.$options.data().clientAppSearchForm.pageIndex;
      this.loadClientAppList();
    },

    // 加载第三方客户列表
    async loadClientDeatilsList() {
      try {
        let count = await this.$api.clientDetails.findMax(this.searchForm);
        let result = await this.$api.clientDetails.findList(this.searchForm);
        this.option.total = count.value;
        this.tableData = result.value;
        this.option.loading = false;
      } catch (error) {
        if (error.description) {
          console.log(error);
        }
        this.option.loading = false;
      }
    },

    // 加载第三方客户应用
    async loadClientAppList() {
      try {
        if(!this.clientAppSearchForm.clientId || this.clientAppSearchForm.clientId === '') {
          this.clientAppOption.loading = false;
          return ;
        }
        let count = await this.$api.clientApp.findMax(this.clientAppSearchForm);
        let result = await this.$api.clientApp.findList(this.clientAppSearchForm);
        this.clientAppOption.total = count.value;
        this.clientAppTableData = result.value;
        this.clientAppOption.loading = false;
      } catch (error) {
        if (error.description) {
          console.log(error);
        }
        this.clientAppOption.loading = false;
      }
    },

    // 打开弹窗
    openDialog(modelType, modelData) {
      this.modelType = modelType;
      if (modelData === undefined) {
        this.modelData = {
          accessTokenValidity: 7200,
          refreshTokenValidity: 604800,
          resourceIdsList: [{ resourceIds: 'gate_way_server', index: 0 }],
          scopeList: [{ scope: 'user_info', index: 0 }],
          enable: 1,
          clientId: '',
          clientSecret: '',
          saltValue: 'dondown',
          saltOrder: 1
        }
      } else {
        modelData['resourceIdsList'] = [];
        modelData['scopeList'] = [];
        this.modelData = JSON.parse(JSON.stringify(modelData))
      }
      this.clientDetailsHandleDialogVisible = true;
    },

    // 打开弹窗（客户应用）
    openClientAppDialog(modelType, modelData) {
      this.clientAppModelType = modelType
      if (modelData === undefined) {
        this.clientAppModelData = {
          name: '',
        }
      } else {
        this.clientAppModelData = JSON.parse(JSON.stringify(modelData))
      }
      this.clientAppHandleDialogVisible = true;
    },

    // 点击表格单行
    rowClick(row, column, event) {
      console.log("点击表格单行");
      this.clientAppSearchForm.clientId = row.id;
      this.clientAppSearchForm.name = row.name;
      this.loadClientAppList();
    },

    // 启用状态切换
    enabledChange(row, value) {
      let formData = row;
      let loadTip = value === 1 ? '启用' : '禁用';
      this.$confirm(`此操作将${loadTip} ${row.manufacture} 客户端，是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$api.clientDetails
            .update(formData)
            .then((res) => {
              this.$message.success(`成功${loadTip}`);
            })
            .catch((error) => {
              console.log(error);
            });
        })
        .catch(() => {
          row.enable = value === 1 ? 0 : 1;
          this.$message.info(`已取消${loadTip}`);
        });
    },

    // 应用启用状态切换
    enabledAppChange(row, value) {
      let formData = row;
      let loadTip = value === 1 ? '启用' : '禁用';
      this.$confirm(`此操作将${loadTip} ${row.name} 应用，是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$api.clientApp
            .update(formData)
            .then((res) => {
              this.$message.success(`成功${loadTip}`);
            })
            .catch((error) => {
              console.log(error);
            });
        })
        .catch(() => {
          row.enable = value === 1 ? 0 : 1;
          this.$message.info(`已取消${loadTip}`);
        });
    },

    // 应用启用状态切换
    trimAppChange(row, value) {
      let formData = row;
      let loadTip = value === 1 ? '去除' : '保留';
      this.$confirm(`此操作将${loadTip} ${row.name} 应用代理前缀，是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$api.clientApp
            .update(formData)
            .then((res) => {
              this.$message.success(`成功${loadTip}应用代理前缀`);
            })
            .catch((error) => {
              console.log(error);
            });
        })
        .catch(() => {
          row.trim = value === 1 ? 0 : 1;
          this.$message.info(`已取消${loadTip}`);
        });
    },

    // 更新密钥
    handleUpdateClientSecret(row) {
      this.modelData = row;
      if (!this.modelData.clientSecret) {
        this.modelData.clientSecret = '';
      }
      console.log(this.modelData)
      this.updateClientSecretDialogVisible = true;
    },

    // 删除
    handleDelete(index, row) {
      let _this = this;
      this.$confirm(`此操作将永久删除 "${row.manufacture}" 客户, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose(action, instance, done) {
          if (action == 'confirm') {
            this.$api.clientDetails
              .del(row.id)
              .then((res) => {
                this.$message.success('删除成功');
                done();
                _this.loadClientDeatilsList();
              })
              .catch((error) => {
                console.log(error);
              });
          } else {
            done();
          }
        },
      })
        .then(() => { })
        .catch((err) => {
          this.$message.info('已取消删除');
        });
    },

    handleClientAppDelete(index, row) {
      let _this = this;
      this.$confirm(`此操作将永久删除 "${row.name}" 应用, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose(action, instance, done) {
          if (action == 'confirm') {
            this.$api.clientApp
              .del(row.id)
              .then((res) => {
                this.$message.success('删除成功');
                done();
                _this.loadClientAppList();
              })
              .catch((error) => {
                console.log(error);
              });
          } else {
            done();
          }
        },
      })
        .then(() => { })
        .catch((err) => {
          this.$message.info('已取消删除');
        });
    },

  },
};
</script>

<style lang='scss' scoped>.box-card {
  margin-bottom: 20px;
}</style>
